package com.visionet.school.app.web.service.entrust;

import com.visionet.school.app.web.common.utilities.props.PropsKeys;
import com.visionet.school.app.web.common.utilities.props.PropsUtil;
import com.visionet.school.app.web.common.utils.DownLoadFileUtils;
import com.visionet.school.app.web.common.utils.PageUtils;
import com.visionet.school.app.web.common.web.WebContextFactory;
import com.visionet.school.app.web.entity.entrust.Entrust;
import com.visionet.school.app.web.entity.entrust.vo.EntrustVo;
import com.visionet.school.app.web.entity.enums.EntrustEnums;
import com.visionet.school.app.web.entity.enums.FileEnums;
import com.visionet.school.app.web.entity.enums.MemberType;
import com.visionet.school.app.web.entity.file.FileClass;
import com.visionet.school.app.web.entity.file.vo.FileVo;
import com.visionet.school.app.web.entity.member.Member;
import com.visionet.school.app.web.entity.member.MemberClass;
import com.visionet.school.app.web.entity.member.MemberFile;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.repository.entrust.EntrustRepository;
import com.visionet.school.app.web.repository.file.FileClassRepository;
import com.visionet.school.app.web.repository.member.MemberClassRepository;
import com.visionet.school.app.web.repository.member.MemberFileRepository;
import com.visionet.school.app.web.repository.member.MemberRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by hxpeng on 2017/3/2.
 */

@Service
public class EntrustService {

    private static final Logger logger = LoggerFactory.getLogger(EntrustService.class);

    @Resource
    private EntrustRepository entrustRepository;
    @Resource
    private MemberRepository memberRepository;
    @Resource
    private MemberClassRepository memberClassRepository;
    @Resource
    private FileClassRepository fileClassRepository;
    @Resource
    private MemberFileRepository memberFileRepository;

    public Map<String, Object> getEntrustPage(final EntrustVo entrustVo, String sortType){

        List<Sort.Order> orders =new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, sortType));//嘱托时间排序
        orders.add(new Sort.Order(Sort.Direction. DESC, "importantState"));//重要嘱托排序
        Pageable pageable = PageUtils.buildPageRequest(entrustVo.getPageInfo().getPageNumber(), entrustVo.getPageInfo().getPageSize(), new Sort(orders));
        Page<Entrust> objPage = entrustRepository.findAll(new Specification<Entrust>() {
            public Predicate toPredicate(Root<Entrust> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> lstPredicates = new ArrayList<>();
                if (StringUtils.isNotBlank(entrustVo.getEntrustState())) {
                    lstPredicates.add(cb.equal(root.get("entrustState"), entrustVo.getEntrustState()));
                }
                List<String> studentIds = entrustVo.getStudentIds();
                if (studentIds != null && studentIds.size() > 0) {
                    Expression<String> exp = root.get("toEntrustChildId");
                    lstPredicates.add(exp.in(studentIds));
                }
                if (StringUtils.isNotBlank(entrustVo.getToEntrustId())) {
                    lstPredicates.add(cb.equal(root.get("toEntrustId"), entrustVo.getToEntrustId()));
                }
                lstPredicates.add(cb.equal(root.get("isDeleted"), "0"));
                Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
                return cb.and(lstPredicates.toArray(arrayPredicates));
            }
        }, pageable);
        return PageUtils.getPageMap(objPage);
    }


    public EntrustVo getEntrustInfo(String entrustId){
        Entrust entrust = entrustRepository.getEntrustInfo(entrustId);
        if(entrust != null){
            EntrustVo entrustVo = new EntrustVo();
            BeanUtils.copyProperties(entrust,entrustVo);
            return entrustVo;
        }
        return null;
    }


    /**
     * 保存嘱托
     * @param entrustVo
     */
    public void save(EntrustVo entrustVo){
        try {
            LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
//            LoginAccountVo loginAccountVo = new LoginAccountVo();
//            loginAccountVo.setMemberId("A83FA905F6044E9CA30C52FDCD351794");
//            loginAccountVo.setMemberName("张泽奇");

            String memberId = loginAccountVo.getMemberId();
            String entrustAudioPath = null;

            if(entrustVo.getEntrustType().equals(EntrustEnums.AUDIO.toKey()) && StringUtils.isNotBlank(entrustVo.getMediaId())){
                //下载音频
                StringBuffer stringBuffer = new StringBuffer(PropsUtil.getProperty(PropsKeys.SERVER_AUDIO_PATH));
                stringBuffer.append("/").append(memberId);
                stringBuffer.append("_").append(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                FileVo fileVo = DownLoadFileUtils.downloadWechatFile(entrustVo.getMediaId(),stringBuffer.toString(),false, FileEnums.AUDIO.toKey());
                //保存文件
                FileClass fileClass = new FileClass();
                BeanUtils.copyProperties(fileVo,fileClass);
                fileClass.setIsDeleted("0");
                fileClass = fileClassRepository.save(fileClass);
                MemberFile memberFile = new MemberFile();
                memberFile.setMemberId(memberId);
                memberFile.setFileId(fileClass.getId());
                memberFile.setIsDeleted("0");
                memberFileRepository.save(memberFile);
                entrustAudioPath = fileVo.getFilePath();
            }

            if(StringUtils.isNotBlank(entrustVo.getId())){
                Entrust entrust = entrustRepository.findOne(entrustVo.getId());
                entrust.setEntrustContent(entrustVo.getEntrustContent());
                entrust.setImportantState(entrustVo.getImportantState());
                entrust.setEntrustType(entrustVo.getEntrustType());
                entrust.setEntrustAudioPath(entrustAudioPath);
                entrustRepository.save(entrust);
            }else{
                //循环给多位宝宝添加嘱托
                for (String strings : entrustVo.getStudentIds()){
                    Member student;
                    Member teacher;
                    student = memberRepository.findOne(strings);
                    //查询宝宝所在班级
                    MemberClass memberClass = memberClassRepository.findOneByMemberId(student.getId());
                    if(memberClass == null){
                        throw new RuntimeException("宝宝还未被添加进班级哦！");
                    }
                    //查询班级关系表获取老师成员Id
                    List<MemberClass> list = memberClassRepository.findListByClassId(memberClass.getClassId(), MemberType.TEACHER.toKey());
                    if(list == null || list.size() < 1){
                        throw new RuntimeException("该班级暂无班主任！");
                    }
                    String teacherId = list.get(0).getMemberId();
                    teacher = memberRepository.findOne(teacherId);
                    if(teacher == null){
                        throw new RuntimeException("找不到被嘱托人");
                    }
                    Entrust entrust = new Entrust();
                    //COPY包括文字嘱托正文
                    BeanUtils.copyProperties(entrustVo,entrust);
                    //嘱托对象
                    entrust.setToEntrustChildId(student.getId());
                    entrust.setToEntrustChildName(student.getMemberName());
                    //被嘱托人
                    entrust.setToEntrustName(teacher.getMemberName());
                    entrust.setToEntrustId(teacherId);
                    //嘱托人
                    entrust.setEntrustId(memberId);
                    entrust.setEntrustName(loginAccountVo.getMemberName());

                    entrust.setEntrustTime(new Date());
                    entrust.setEntrustState(EntrustEnums.UNEXECUTED.toKey());
                    entrust.setIsDeleted("0");
                    entrust.setEntrustAudioPath(entrustAudioPath);
                    entrustRepository.save(entrust);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("保存嘱托失败");
        }
    }

    /**
     * 嘱托确认回执
     * @param entrustId
     */
    public void updateExecutedEntrust(String entrustId){
        Entrust entrust = entrustRepository.findOne(entrustId);
        if(null == entrust){
            throw new RuntimeException("未找到要确认执行的嘱托");
        }
        entrust.setEntrustState(EntrustEnums.EXECUTE.toKey());
        entrust.setExecuteTime(new Date());
        entrustRepository.save(entrust);
    }

}
